﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace search
{
	/// <summary>
	/// SSearch 的摘要说明。
	/// </summary>
	public partial class SSearch : System.Web.UI.Page
	{
		private const int PAGE_SIZE = 3;
		private bool flag = true;
		private DataSet dsPostBible;

	
		protected void Page_Load(object sender, System.EventArgs e)
		{
			// 在此处放置用户代码以初始化页面
			dsPostBible = SearchDataAccess.GetPostBible();

			if(!Page.IsPostBack)
			{
				this.TextBox2.Attributes["onkeydown"] = "return check2(event); ";
				this.TextBox3.Attributes["onkeydown"] = "return check3(event);";
				this.TextBox2.Attributes["onkeyup"] = "document.all('TextBox4').value=document.all('TextBox2').value; ";
				this.TextBox3.Attributes["onkeyup"] = "document.all('TextBox5').value=document.all('TextBox3').value; ";
				this.TextBox4.Attributes["onkeypress"] = "return check45(event);";
				this.TextBox5.Attributes["onkeypress"] = "return check45(event);";

				CheckUser();
				this.Button_Submit.Attributes["onclick"] = "return checkinput();";
				BindDropDownList();
			}
		}

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.DataList1.ItemDataBound += new System.Web.UI.WebControls.DataListItemEventHandler(this.DataList1_ItemDataBound);

		}
		#endregion

		private void CheckUser()
		{
			
			this.Literal_Admin.Text = "";
			HttpCookie cookie = Request.Cookies["Email"];
			if(cookie == null)
			{
				return;
			}
			DataSet ds = SearchDataAccess.GetUserRoles(cookie.Value);
			ds.Tables[0].DefaultView.RowFilter = "RoleID=4";
			if(ds.Tables[0].DefaultView.Count > 0)
			{
				this.Literal_Admin.Text = "<FONT color='#ffffff'>&nbsp;| </FONT><A href='AdminArticle.aspx'><FONT color='#ffffff'>发帖审核</FONT></A>";
			}
		}


		private void BindDropDownList()
		{
			DataSet ds = BibleToolsDataAccess.GetBibleTitles();
			this.DropDownList1.DataTextField = "Title_CN";
			this.DropDownList1.DataValueField = "Title_CN";
			this.DropDownList1.DataSource = ds.Tables[0].DefaultView;
			this.DropDownList1.DataBind();
		}

        protected void Button_Submit_Click1(object sender, EventArgs e)
		{
			if(!CheckInput())
				return;

			DataSet ds = SearchDataAccess.GetArticlesByScripture(this.DropDownList1.SelectedValue,
				Convert.ToInt32(this.TextBox2.Text), Convert.ToInt32(this.TextBox3.Text),
				Convert.ToInt32(this.TextBox4.Text), Convert.ToInt32(this.TextBox5.Text));

			this.Label_LeftResult.Text = "搜索结果：&nbsp;&nbsp;&nbsp;&nbsp;<font color='#cc0000'>" + this.DropDownList1.SelectedValue +
				this.TextBox2.Text + "∶" + this.TextBox3.Text + "&nbsp;—&nbsp;" + this.TextBox4.Text + "∶" + this.TextBox5.Text + "</font>";

			this.Label_RightResult.Text = ds.Tables[0].Rows.Count.ToString() + "篇文章";

			if(ds.Tables[0].Rows.Count <= PAGE_SIZE)
			{
				this.DropDownList_Page.Visible = false;
				this.DropDownList_Pageb.Visible = false;
				this.Linkbutton_Nextpage.Visible = false;
				this.LinkButton_NextpageB.Visible = false;
				this.LinkButton_Prepage.Visible = false;
				this.LinkButton_PrepageB.Visible = false;
			}
			else
			{
				this.DropDownList_Page.Visible = true;
				this.DropDownList_Pageb.Visible = true;
				this.Linkbutton_Nextpage.Visible = true;
				this.LinkButton_NextpageB.Visible = true;

				int recnum = ds.Tables[0].Rows.Count;
				int page = recnum / PAGE_SIZE;
				if(recnum % PAGE_SIZE > 0)
					page += 1;

				this.DropDownList_Page.Items.Clear();
				this.DropDownList_Pageb.Items.Clear();
				for(int i = 1; i <= page; i++)
				{
					this.DropDownList_Page.Items.Add(new ListItem("Page " + i.ToString() + " of " + page.ToString() + "  ", i.ToString()));
					this.DropDownList_Pageb.Items.Add(new ListItem("Page " + i.ToString() + " of " + page.ToString() + "  ", i.ToString()));
				}
				
				for(int j = PAGE_SIZE; j < ds.Tables[0].Rows.Count; j++)
				{
					ds.Tables[0].Rows[j]["PostID"] = 0;
				}
				ds.Tables[0].DefaultView.RowFilter = "PostID>0";
			}


			this.DataList1.DataSource = ds.Tables[0].DefaultView;
			this.DataList1.DataBind();

			if(ds.Tables[0].Rows.Count > 0)
			{
				this.Literal_ScrollToTop.Text = "<a href='javascript:window.scrollTo(0,0);'>回本页顶</a>";
																												   }
			else
			{
				this.Literal_ScrollToTop.Text = "";
			}
		}


		private void DataList1_ItemDataBound(object sender, System.Web.UI.WebControls.DataListItemEventArgs e)
		{
			if(e.Item.ItemIndex < 0)
				return;

			DataRowView drv = (DataRowView)e.Item.DataItem;
			Literal objLiteral = (Literal)e.Item.FindControl("Literal_Article");
			objLiteral.Text = "<table border=0 cellpadding=0 cellspacing=0 width='100%'>";
			if(e.Item.ItemIndex == 0)
			{
				objLiteral.Text += "<tr><td height=2 colspan=2 bgcolor='#0033cc'></td></tr>";
			}
			objLiteral.Text += "<tr><td width='100%' height=25>";
			
			if(drv.Row["url"] == DBNull.Value || drv.Row["url"].ToString() == "")
			{
				objLiteral.Text += "<a class=a1 href='Article.aspx?id=" + drv.Row["PostID"].ToString() + "' target=_blank><font size=+1>" + drv.Row["Subject"].ToString() + "</font></a>";
			}
			else
			{
				objLiteral.Text += "<a class=a1 href='" + drv.Row["url"].ToString() + "' target=_blank>" + drv.Row["Subject"].ToString() + "</a>";
			}
			objLiteral.Text += "</td><td nowrap>";
			//objLiteral.Text += "<a href='AllArticles.aspx?id=" + drv.Row["UserID"].ToString() + "&name=" + Server.UrlEncode(drv.Row["NickName"].ToString()) + "' target=_blank>" + drv.Row["NickName"].ToString() + "</a>";
			objLiteral.Text += "</td></tr>\n";

			objLiteral.Text += "<tr><td height=25 colspan=2>";
			objLiteral.Text += "<a class=a1 href='BibleTools.aspx?title=" + Server.UrlEncode(drv.Row["BibleTitle"].ToString()) + "&c=" + drv.Row["BibleChapter"].ToString() + "&s=" + drv.Row["BibleSection"].ToString() + "&c1=" + drv.Row["BibleChapter_To"].ToString() + "&s1=" + drv.Row["BibleSection_To"].ToString() + "' target=_blank>" +
								drv.Row["BibleTitle"].ToString() + "&nbsp;" + drv.Row["BibleChapter"].ToString() + "∶" + drv.Row["BibleSection"].ToString() + "&nbsp;—&nbsp;" + 
								drv.Row["BibleChapter_To"].ToString() + "∶" + drv.Row["BibleSection_To"].ToString() + "</a>";
			DataView view = dsPostBible.Tables[0].DefaultView;
			view.RowFilter = "PostID=" + drv.Row["PostID"].ToString();
			for(int i = 0; i < view.Count; i++)
			{
				objLiteral.Text += "&nbsp;&nbsp;<a class=a1 href='BibleTools.aspx?title=" + Server.UrlEncode(view[i].Row["BibleTitle"].ToString()) + "&c=" + view[i].Row["BibleChapter"].ToString() + "&s=" + view[i].Row["BibleSection"].ToString() + "&c1=" + view[i].Row["BibleChapter_To"].ToString() + "&s1=" + view[i].Row["BibleSection_To"].ToString() + "' target=_blank>" +
					view[i].Row["BibleTitle"].ToString() + "&nbsp;" + view[i].Row["BibleChapter"].ToString() + "∶" + view[i].Row["BibleSection"].ToString() + "&nbsp;—&nbsp;" + 
					view[i].Row["BibleChapter_To"].ToString() + "∶" + view[i].Row["BibleSection_To"].ToString() + "</a>";
			}

			objLiteral.Text += "</td></tr>\n"; 
			if(drv.Row["Summary"].ToString() == "")
			{
				objLiteral.Text += "<tr><td height=25 colspan=2 style='TEXT-HEIGHT:150%;'>" + (drv.Row["Body"].ToString().Length>200?drv.Row["Body"].ToString().Substring(0,200):drv.Row["Body"].ToString().ToString()) + "</td></tr>\n";
			}
			else
			{
				objLiteral.Text += "<tr><td height=25 colspan=2 style='FONT-SIZE:12px; TEXT-HEIGHT:150%;'>" + drv.Row["Summary"].ToString() + "</td></tr>\n";
			}
			
			int numberofvisits = Convert.ToInt32(drv.Row["NumberOfVisits"]);
			int numberofyes, numberofno;
			if(drv.Row["Vote_yes"] == DBNull.Value)
				numberofyes = 0;
			else
				numberofyes = Convert.ToInt32(drv.Row["Vote_yes"]);

			if(drv.Row["Vote_no"] == DBNull.Value)
				numberofno = 0;
			else
				numberofno = Convert.ToInt32(drv.Row["Vote_no"]);
//			if(numberofyes > numberofvisits)
//				numberofvisits = numberofyes;

			numberofvisits = numberofno + numberofyes;
			if(numberofyes > 0 && numberofvisits > 0)
			{
				decimal p = Convert.ToDecimal(numberofyes) / Convert.ToDecimal(numberofvisits);
				objLiteral.Text += "<tr><td height=25 colspan=2 style='COLOR:#003399'>" + numberofvisits.ToString() + "位读者中" +
					numberofyes.ToString() + "位（" + p.ToString("P") + "）认为本文对他们有帮助</td></tr>\n";
			}

			objLiteral.Text += "<tr><td height=2 colspan=2 bgcolor='#0033cc'></td></tr><tr><td height=10 colspan=2></td></tr></table>\n"; 
		}


		private bool CheckInput()
		{
			string s = this.TextBox2.Text.Trim();

			if(s.Length == 0)
			{
				this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox2').focus();</script>";
				return false;
			}
			else
			{
				try
				{
					int chap1 = Convert.ToInt32(s);
				}
				catch
				{
					this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox2').focus();</script>";
					return false;
				}
			}

			s = this.TextBox3.Text.Trim();
			if(s.Length == 0)
			{
				this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox3').focus();</script>";
				return false;
			}
			else
			{
				try
				{
					int chap1 = Convert.ToInt32(s);
				}
				catch
				{
					this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox3').focus();</script>";
					return false;
				}
			}

			s = this.TextBox4.Text.Trim();
			if(s.Length == 0)
			{
				this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox4').focus();</script>";
				return false;
			}
			else
			{
				try
				{
					int chap1 = Convert.ToInt32(s);
				}
				catch
				{
					this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox4').focus();</script>";
					return false;
				}
			}
			
			s = this.TextBox5.Text.Trim();
			if(s.Length == 0)
			{
				this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox5').focus();</script>";
				return false;
			}
			else
			{
				try
				{
					int chap1 = Convert.ToInt32(s);
				}
				catch
				{
					this.Literal_script.Text = "<script defer>alert('请输入经文章节！');document.all('TextBox5').focus();</script>";
					return false;
				}
			}


			return true;
		}

		protected void DropDownList_Page_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(flag)
				GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue));
		}

		protected void DropDownList_Pageb_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(flag)
				GoPage(Convert.ToInt32(this.DropDownList_Pageb.SelectedValue));
		}


		private void GoPage(int page)
		{
			
			flag = false;
			this.DropDownList_Page.SelectedValue = page.ToString();
			this.DropDownList_Pageb.SelectedValue = page.ToString();
			flag = true;

			DataSet ds = SearchDataAccess.GetArticlesByScripture(this.DropDownList1.SelectedValue,
				Convert.ToInt32(this.TextBox2.Text), Convert.ToInt32(this.TextBox3.Text),
				Convert.ToInt32(this.TextBox4.Text), Convert.ToInt32(this.TextBox5.Text));

			if(page == 1)
			{
				this.LinkButton_Prepage.Visible = false;
				this.LinkButton_PrepageB.Visible = false;
			}
			else
			{
				this.LinkButton_Prepage.Visible = true;
				this.LinkButton_PrepageB.Visible = true;
			}
			if(page.ToString() == this.DropDownList_Page.Items[this.DropDownList_Page.Items.Count - 1].Value)
			{
				this.Linkbutton_Nextpage.Visible = false;
				this.LinkButton_NextpageB.Visible = false;
			}
			else
			{
				this.Linkbutton_Nextpage.Visible = true;
				this.LinkButton_NextpageB.Visible = true;
			}

			for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
			{
				if(i < PAGE_SIZE * (page - 1) || i > PAGE_SIZE * page - 1)
				{
					ds.Tables[0].Rows[i]["PostID"] = 0;
				}
			}

			ds.Tables[0].DefaultView.RowFilter = "PostID>0";
			this.DataList1.DataSource = ds.Tables[0].DefaultView;
			this.DataList1.DataBind();
		}

        protected void LinkButton_Prepage_Click1(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) - 1);
        }

        protected void Linkbutton_Nextpage_Click1(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) + 1);
        }

        protected void LinkButton_PrepageB_Click1(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) - 1);
        }

        protected void LinkButton_NextpageB_Click1(object sender, EventArgs e)
        {
            GoPage(Convert.ToInt32(this.DropDownList_Page.SelectedValue) + 1);
        }

     

	}
}
